package com.summer.dingding.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.CorpMessageCorpconversationAsyncsendRequest;
import com.dingtalk.api.request.OapiDepartmentListIdsRequest;
import com.dingtalk.api.request.OapiDepartmentListRequest;
import com.dingtalk.api.request.OapiSnsGetPersistentCodeRequest;
import com.dingtalk.api.request.OapiSnsGetSnsTokenRequest;
import com.dingtalk.api.request.OapiSnsGetuserinfoRequest;
import com.dingtalk.api.request.OapiUserGetRequest;
import com.dingtalk.api.request.OapiUserGetUseridByUnionidRequest;
import com.dingtalk.api.response.CorpMessageCorpconversationAsyncsendResponse;
import com.dingtalk.api.response.OapiDepartmentListIdsResponse;
import com.dingtalk.api.response.OapiDepartmentListResponse;
import com.dingtalk.api.response.OapiSnsGetPersistentCodeResponse;
import com.dingtalk.api.response.OapiSnsGetSnsTokenResponse;
import com.dingtalk.api.response.OapiSnsGetuserinfoResponse;
import com.dingtalk.api.response.OapiUserGetResponse;
import com.dingtalk.api.response.OapiUserGetUseridByUnionidResponse;
import com.summer.dingding.model.DingDingMessageTemplate;
import com.summer.dingding.service.DingDingService;
import com.summer.dingding.util.DingDingConstants;
import com.summer.dingding.util.DingDingUtil;
import com.taobao.api.ApiException;

/**
 * 
 */
@Service("dingDingService")
public class DingDingServiceImpl implements DingDingService {

	@Override
	public JSONObject goDingLogin(String code) {
		try {
			// 获取accesstoken
			String accessToken = DingDingUtil.getAccesstoken(
					DingDingConstants.Config.CodeLogin.APPID,
					DingDingConstants.Config.CodeLogin.APP_SECRET);
			// 获取用户授权的持久授权码
			JSONObject json = getPersistentCode(accessToken, code);
			String openId = "";
			String persistentCode = "";
			if (null != json) {
				openId = json.getString("openid");
				persistentCode = json.getString("persistent_code");
			}

			// 获取用户授权的SNS_TOKEN
			String snsToken = getSnsToken(accessToken, openId, persistentCode);
			// 获取用户unionid
			// String unionId = getUnionId(snsToken);
			// 根据unionid获取用户userId
			String appAccessToken = DingDingUtil.getAppAccesstoken();
			JSONObject userInfo = getUserInfo(snsToken);
			String userId = getUserId(appAccessToken,
					userInfo.getString("unionid"));
			// 获取用户详细数据
			JSONObject userData = getUserData(appAccessToken, userId);
			return userData;
		} catch (Exception e) {

		}
		return null;
	}

	/**
	 * 发送消息
	 * @author	Summer
	 * @Date	2018年12月2日
	 * @param agentId
	 *            微应用的ID
	 * @param userId
	 *            接收者的用户userid列表
	 * @param msgcontent
	 *            消息内容
	 */
	@Override
	public JSONObject sendDDMessage(String userId,
			DingDingMessageTemplate message) {
		DingTalkClient client = new DefaultDingTalkClient(
				"https://eco.taobao.com/router/rest");
		CorpMessageCorpconversationAsyncsendRequest req = new CorpMessageCorpconversationAsyncsendRequest();
		req.setMsgtype("oa"); // 消息类型
		req.setAgentId(DingDingConstants.Config.AGENTID);
		req.setUseridList(userId);
		req.setToAllUser(false); // 是否发送给企业全部用户
		req.setMsgcontentString(JSONObject.toJSONString(message));
		try {
			String token = DingDingUtil.getAppAccesstoken();
			CorpMessageCorpconversationAsyncsendResponse rsp = client.execute(
					req, token);
			JSONObject json = JSONObject.parseObject(JSONObject
					.toJSONString(rsp.getResult()));
			if (json != null) {
				return json;
			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String getDepartment(String accessToken) throws ApiException {
		DingTalkClient client = new DefaultDingTalkClient(
				"https://oapi.dingtalk.com/department/list_ids");
		OapiDepartmentListIdsRequest request = new OapiDepartmentListIdsRequest();
		request.setId("1");
		request.setHttpMethod("GET");
		OapiDepartmentListIdsResponse response = client.execute(request,
				accessToken);

		return response.getBody();
	}

	public JSONObject getDepartmentDetail(String accessToken)
			throws ApiException {
		DingTalkClient client = new DefaultDingTalkClient(
				"https://oapi.dingtalk.com/department/list");
		OapiDepartmentListRequest request = new OapiDepartmentListRequest();
		request.setId("");
		request.setFetchChild(true);
		request.setHttpMethod("GET");

		OapiDepartmentListResponse response = client.execute(request,
				accessToken);

		JSONObject json = JSONObject.parseObject(response.getBody());

		return json;
	}

	/**
	 * 获取用户持久授权码
	 * 
	 * @param accessToken
	 * @param code
	 * @return
	 * @throws ApiException
	 */
	public JSONObject getPersistentCode(String accessToken, String code)
			throws ApiException {

		DingTalkClient client = new DefaultDingTalkClient(
				"https://oapi.dingtalk.com/sns/get_persistent_code");
		OapiSnsGetPersistentCodeRequest request = new OapiSnsGetPersistentCodeRequest();
		request.setTmpAuthCode(code);
		OapiSnsGetPersistentCodeResponse response = client.execute(request,
				accessToken);

		JSONObject json = JSONObject.parseObject(response.getBody());
		if (null != json) {
			if (response.isSuccess()) {
				return json;
			}
		}
		return null;
	}

	public String getSnsToken(String accessToken, String openid,
			String persistent_code) throws ApiException {

		DingTalkClient client = new DefaultDingTalkClient(
				"https://oapi.dingtalk.com/sns/get_sns_token");
		OapiSnsGetSnsTokenRequest request = new OapiSnsGetSnsTokenRequest();
		request.setOpenid(openid);
		request.setPersistentCode(persistent_code);
		OapiSnsGetSnsTokenResponse response = client.execute(request,
				accessToken);

		JSONObject json = JSONObject.parseObject(response.getBody());
		if (null != json) {
			if (Integer.parseInt(json.get("errcode").toString()) == 0) {
				String snsToken = json.getString("sns_token");
				return snsToken;
			}
		}
		return null;
	}

	public JSONObject getUserInfo(String snsToken) throws ApiException {

		DingTalkClient client = new DefaultDingTalkClient(
				"https://oapi.dingtalk.com/sns/getuserinfo");
		OapiSnsGetuserinfoRequest request = new OapiSnsGetuserinfoRequest();
		request.setSnsToken(snsToken);
		request.setHttpMethod("GET");
		OapiSnsGetuserinfoResponse response = client.execute(request);
		JSONObject json = JSONObject.parseObject(response.getBody());
		if (null != json) {
			if (Integer.parseInt(json.get("errcode").toString()) == 0) {
				JSONObject jsonUser = json.getJSONObject("user_info");
				return jsonUser;
			}
		}
		return null;
	}

	public String getUserId(String accessToken, String unionId)
			throws ApiException {
		DingTalkClient client = new DefaultDingTalkClient(
				"https://oapi.dingtalk.com/user/getUseridByUnionid");
		OapiUserGetUseridByUnionidRequest request = new OapiUserGetUseridByUnionidRequest();
		request.setUnionid(unionId);
		request.setHttpMethod("GET");

		OapiUserGetUseridByUnionidResponse response = client.execute(request,
				accessToken);
		JSONObject json = JSONObject.parseObject(response.getBody());
		if (null != json) {
			if (Integer.parseInt(json.get("errcode").toString()) == 0) {
				String userId = json.getString("userid");
				return userId;
			}
		}
		return "";
	}

	//
	public JSONObject getUserData(String accessToken, String userId)
			throws ApiException {

		DingTalkClient client = new DefaultDingTalkClient(
				"https://oapi.dingtalk.com/user/get");
		OapiUserGetRequest request = new OapiUserGetRequest();
		request.setUserid(userId);
		request.setHttpMethod("GET");
		OapiUserGetResponse response = client.execute(request, accessToken);

		// String url = "https://oapi.dingtalk.com/user/get?access_token=" +
		// accessToken + "&userid=" + userId;
		JSONObject json = JSONObject.parseObject(response.getBody());
		if (null != json) {
			if (Integer.parseInt(json.get("errcode").toString()) == 0) {
				return json;
			}
		}
		return null;
	}

	// private JSONObject ossHttpGetUtil(String url) {
	// HttpGet httpGet = new HttpGet(url);
	// HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
	// HttpClient httpClient = httpClientBuilder.build();
	// HttpResponse httpResponse = null;
	// try {
	// httpResponse = httpClient.execute(httpGet);
	// } catch (Exception e) {
	// }
	// BufferedReader bufferedReader = null;
	// StringBuilder entityStringBuilder = new StringBuilder();
	// // 得到httpResponse的状态响应码
	// int statusCode = httpResponse.getStatusLine().getStatusCode();
	// JSONObject jsonObject = null;
	// String access_token = "";
	// if (statusCode == HttpStatus.SC_OK) {
	// // 得到httpResponse的实体数据
	// HttpEntity httpEntity = httpResponse.getEntity();
	// if (httpEntity != null) {
	// try {
	// return jsonObject =
	// JSONObject.parseObject(EntityUtils.toString(httpEntity));
	// } catch (Exception e) {
	//
	// }
	// }
	// }
	// return null;
	// }

	// private JSONObject ossHttpPostUtil(String url, JSONObject json) {
	// HttpPost httpPost = new HttpPost(url);
	// HttpEntity httpEntity = null;
	// httpEntity = new StringEntity(json.toString(), "UTF-8");
	// httpPost.setEntity(httpEntity);
	// HttpResponse httpResponse = null;
	// HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
	// HttpClient httpClient = httpClientBuilder.build();
	// try {
	// httpResponse = httpClient.execute(httpPost);
	// } catch (Exception e) {
	//
	// }
	// StringBuilder entityStringBuilder = new StringBuilder();
	// // 得到httpResponse的状态响应码
	// int statusCode = httpResponse.getStatusLine().getStatusCode();
	// if (statusCode == HttpStatus.SC_OK) {
	// // 得到httpResponse的实体数据
	// HttpEntity httpEntity2 = httpResponse.getEntity();
	// JSONObject jsonObject = null;
	// if (httpEntity2 != null) {
	// try {
	// return jsonObject =
	// jsonObject.parseObject(EntityUtils.toString(httpEntity2));
	// } catch (Exception e) {
	//
	// }
	// }
	// }
	// return null;
	// }

}